package com.zrh.jsd.service.studydemo.common_test;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CommonException1 {
    volatile static int a = 1;
    volatile static int b = 1;

    // add方法始终只有一个线程在操作，显然只为add方法加锁是没用的
    // 为add和compare都加上方法锁，确保add方法执行时，确保compare无法读取a和b
    public static synchronized void add() {
        log.info("add start");
        for (int i = 0; i < 100000; i++) {
            a++;
            b++;
        }
        log.info("add done");
    }

    public static synchronized void compare() {
        log.info("compare start");
        for (int i = 0; i < 100000; i++) {
                //a始终等于b吗？
            if (a < b) {
                log.info("a:{},b:{},{}", a, b, a > b);
                //最后的a>b应该始终是false吗？
            }
        }
        log.info("compare done");
    }

    public static void main(String[] args) {
        new Thread(()->CommonException1.add()).start();
        new Thread(()->CommonException1.compare()).start();
    }
}
